from django.core.paginator import Paginator
from django.shortcuts import render
from django.views import View
from meiduo_mall.apps.contents.utils import get_categories
from goods.models import GoodsCategory, SKU, SPUSpecification, SKUSpecification, GoodsVisitCount
from django.http import JsonResponse
import json
from django_redis import get_redis_connection


# Create your views here.
from order.models import OrderInfo, OrderGoods


class GoodListView(View):
    def get(self, requset, categorie_id, page_num):
        # 1.使用封装的方法获取频道分组数据
        categories = get_categories()

        # 2.面包屑导航
        cat3 = GoodsCategory.objects.get(id=categorie_id)
        cat2 = cat3.parent
        cat1 = cat2.parent
        # 以及分类额外指定路径
        cat1.url = cat1.goodschannel_set.filter()[0].url
        breadcrumb = {}
        breadcrumb['cat1'] = cat1
        breadcrumb['cat2'] = cat2
        breadcrumb['cat3'] = cat3

        # 渲染当前分类下的所有商品

        sort = requset.GET.get('sort')
        if sort is None or sort == 'create_time':
            sort = 'create_time'
            skus = SKU.objects.filter(category_id=categorie_id).order_by('create_time')
        elif sort == 'price':
            skus = SKU.objects.filter(category_id=categorie_id).order_by('price')
        else:
            skus = SKU.objects.filter(category_id=categorie_id).order_by('hot')

        # 分页处理
        page = Paginator(skus, 3)
        page_skus = page.page(page_num)

        data = {
            'categories': categories,  # 频道分类数据
            'breadcrumb': breadcrumb,  # 面包写导航数据
            'page_skus': page_skus,  # 分页后的商品数据
            'category': cat3,  # 分类对象
            'page_num': page_num,  # 当前页数
            'total_page': page.num_pages,  # 总页数
            'sort': sort  # 排序字段
        }
        return render(requset, 'list.html', data)


class GoodsHotView(View):
    def get(self, request, categorie_id):
        data = SKU.objects.filter(category_id=categorie_id).order_by('-sales')
        skus = data[0:3]
        hot_sku_list = []
        for sku in skus:
            hot_sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url
            })
        return JsonResponse({'hot_sku_list': hot_sku_list})


class GoodsDetailView(View):
    def get(self, request, pk):
        # 1.获取商品频道分类
        categories = get_categories()
        # 2.面包屑导航数据
        try:
            sku = SKU.objects.get(id=pk)
        except:
            return JsonResponse({'error': '商品不存在'})
        cat3 = GoodsCategory.objects.get(id=sku.category.id)
        cat2 = cat3.parent
        cat1 = cat2.parent
        # 以及分类额外指定路径
        cat1.url = cat1.goodschannel_set.filter()[0].url
        breadcrumb = {}
        breadcrumb['cat1'] = cat1
        breadcrumb['cat2'] = cat2
        breadcrumb['cat3'] = cat3

        # 3.规格和选项参数
        # 3.1通过spu商品获取当前商品的规格数据
        spu = sku.spu
        specs = spu.specs.all()
        # 3.2 给规格指定选项
        for spec in specs:
            spec.option_list = spec.options.all()
            for option in spec.option_list:
                # 判断遍历的这个选项是否是当前商品的选项
                if option.id == SKUSpecification.objects.get(sku=sku, spec=spec).option_id:
                    option.sku_id = sku.id
                    #
                    #
                else:
                    # 如果不是当前选项
                    other_good = SKU.objects.filter(specs__option_id=option.id)
                    # 查询当前商品的其他规格
                    sku_specs = SKUSpecification.objects.filter(sku=sku)
                    # 获取其他规格选项
                    optionlist = []
                    for sku_spec in sku_specs:
                        optionid = sku_spec.option_id
                        optionlist.append(optionid)
                    other_good1 = SKU.objects.filter(specs__option_id__in=optionlist)
                    good = other_good & other_good1
                    option.sku_id = good[0].id
        data = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'spu': sku.spu,
            'category_id': sku.category.id,
            'specs': specs

        }
        return render(request, 'detail.html', data)


class GoodsVisitView(View):
    def post(self, request, pk):
        # 判断分类是否存在
        try:
            GoodsCategory.objects.get(id=pk)
        except:
            return JsonResponse({'error': '分类不存在'}, status=400)
        try:
            # 判断分类是否保存过
            goodsvisit = GoodsVisitCount.objects.get(category_id=pk)
        except:
            # 商品没有保存
            GoodsVisitCount.objects.create(category_id=pk, count=1)
            return JsonResponse({'massage': 'ok'})

        goodsvisit.count += 1
        goodsvisit.save()

        return JsonResponse({'massage': 'ok'})


class GoodsHistoriesView(View):
    def post(self, request, ):
        data = request.body.decode()
        data_dict = json.loads(data)
        sku_id = data_dict.get('sku_id')
        try:
            SKU.objects.get(id=sku_id)
        except:
            return JsonResponse({"error": '商品不存在'})

        user = request.user
        # 链接redis 进行判断是否浏览过此商品
        client = get_redis_connection('history')
        # 存储过则删除
        client.lrem('history_%s' % user, 0, sku_id)
        # 将浏览记录存入
        client.lpush('history_%s' % user, sku_id)
        # 截取数据库存储数量
        client.ltrim('history_%s' % user, 0, 5)
        return JsonResponse({'massage': 'ok'})

    def get(self,request):

        user = request.user

        client = get_redis_connection('history')
        sku_id=client.lrange('history_%s'%user,0,-1)
        print(sku_id)
        skus = SKU.objects.filter(id__in = sku_id)
        list = []
        for sku in skus:
            list.append({
                'id':sku.id,
                'name':sku.name,
                'price':sku.price,
                'default_image_url':sku.default_image.url

            })
        return JsonResponse({'skus':list})

class GoodsCommentView(View):
    def get(self,request,pk):

        try:
            SKU.objects.filter(id=pk)
        except:
            return JsonResponse({'error':'商品不存在'},status=400)

        goods_comment = OrderGoods.objects.filter(sku_id =pk , is_commented=True)
        goods_comment_list = []
        for good_comment in goods_comment:
            goods_comment_list.append({
                'score': good_comment.score,
                'username':'*****' if good_comment.is_anonymous else good_comment.order.user.username,

                'comment':good_comment.comment
            })

        return JsonResponse({'code':0,'goods_comment_list':goods_comment_list})


